require(['config'],function(){
    require(['jquery','swiper','template','jquery.cookie','jquery.fly','loadHF'],function($,Swiper,template){


        // 一、页面渲染
        const id = $.cookie('id')
        console.log(id);
        $.getJSON(`http://www.xiongmaoyouxuan.com/api/detail?id=${id}&normal=1&sa=`,res=>{
            console.log(res)
            const list = res.data
            console.log(list)
            const html = template('des',{list:list})
            $('main').html(html)

            // 二、轮播图
             new Swiper ('.swiper-container', {
            // direction: 'vertical', // 垂直切换选项/
                effect : 'cube',
                // effect : 'flip',
                autoplay: true,
                loop: true, // 循环模式选项
                // 如果需要分页器
                pagination: {
                el: '.swiper-pagination',
                },
                // 如果需要前进后退按钮
                navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
                },
                // 如果需要滚动条
                scrollbar: {
                el: '.swiper-scrollbar',
                },
                autoplay:{
                    delay: 1500,
                    disableOnInteraction: false
                }
            })   

        })

        // 三、加入购物车
        // 事件委派
        $('main').on('click','.goTB-btn',e=>{
            console.log('加入购物车');
            console.log(e.target);
            const $list = $(e.target).parents('.commodity')
            console.log($list) 

            const curr={
                id: $list.data('id'),
                title: $list.find('.cmd-title').text().trim(),
                price: $list.find('.price').html(),
                num: 1,
                image: $list.data('img')
            }

            console.log(curr)
            const cart = JSON.parse($.cookie('cart')) || []
            console.log(cart)
            const index = cart.findIndex( prod => prod.id == curr.id)
            if( index !== -1){
                cart[index].num +=1
            }else{
                cart.push(curr)
            }
            $.cookie('cart',JSON.stringify(cart),{expire:10,path:'/'})



            // 抛物线加入购物车
            const {top, left} = $('.cart').offset()
            $(`<img src="${curr.image}" style="width: 32px; height: 32px; z-index: 999"/>`).fly({
                start: {
                top: e.clientY,
                left: e.clientX
                },
                end: {
                left,
                top: top - $(document).scrollTop(),
                width: 10,
                height: 10
                },
                onEnd() {
                this.destroy()
                }
            })
        })
    })
})